package com.liang.recommend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liang.recommend.algorithm.Pearson;
import com.liang.recommend.mapper.UserActionMapper;
import com.liang.recommend.pojo.UserAction;
import com.liang.recommend.pojo.UserCoordination2;
import com.liang.recommend.mapper.UserCoordination2Mapper;
import com.liang.recommend.service.UserCoordination2Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 小梁
 * @since 2020-12-03
 */
@Service
public class UserCoordination2ServiceImpl extends ServiceImpl<UserCoordination2Mapper, UserCoordination2> implements UserCoordination2Service {

    @Autowired
    UserActionMapper userActionMapper;

    @Autowired
    UserCoordination2Mapper userCoordination2Mapper;

    @Override
    public int toInsertUserCoordination2(Long userId) {
        int i=0; //成功标志
        Pearson pearson = new Pearson();//皮尔森公式
        QueryWrapper<UserAction> wrapper = new QueryWrapper<UserAction>();
        wrapper.eq("user_id", userId);
        List<UserAction> x = userActionMapper.selectList(wrapper);

        QueryWrapper<UserAction> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DISTINCT user_id");
        List<UserAction> userActions = userActionMapper.selectList(queryWrapper);
        Long temp;
        for (UserAction action : userActions) {
            temp=action.getUserId();
            QueryWrapper<UserAction> wrapper1 = new QueryWrapper<UserAction>();
            wrapper1.eq("user_id", temp);
            if(temp!=userId) {
                double y = pearson.getPearsonCorrelationScore(x, userActionMapper.selectList(wrapper1));
                UserCoordination2 coordination2 = new UserCoordination2();
                coordination2.setType(0L);
                if(y<0){
                    y=-y;
                    coordination2.setType(1L); // 负相关标志为1
                }
                coordination2.setUserId1(userId);
                coordination2.setUserId2(temp);
                coordination2.setDistance(y);
                i = userCoordination2Mapper.insert(coordination2);
            }
        }
        return i;
    }
}
